let validateResult = null; // 存储执行结果

// 是否为chrome页签
function isChromeTabUrl(url) {
    return url && url.indexOf('chrome://') === 0;
}

document.addEventListener('DOMContentLoaded', () => {
    chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
        const currentTab = tabs[0];
        const tabId = currentTab.id;
        chrome.storage.local.get(['validateResult'], (result) => {
            if (chrome.runtime.lastError) {
                console.error('Error reading from chrome.storage.local', chrome.runtime.lastError);
            } else if (result?.validateResult?.tabId === tabId) {
                validateResult = result.validateResult;
                renderResult();
            }
        });
    });
});

// 从storeage中读取配置
async function readFromStorageAsync() {
    return new Promise((resolve, reject) => {
        chrome.storage.local.get(['rules'], (result) => {
            if (chrome.runtime.lastError) {
                console.error('Error reading from chrome.storage.local', chrome.runtime.lastError);
                reject(chrome.runtime.lastError);
            } else {
                resolve(result.rules);
            }
        });
    });
}

// 高亮
function onHighlight(e) {
    const { path, type, index } = e.target.dataset;
    console.log(path, type, index);
    chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
        const currentTab = tabs[0];
        chrome.scripting.executeScript(
            {
                target: { tabId: currentTab.id },
                func: (path, type, index) => {
                    if (typeof uiaActions !== 'undefined') {
                        return uiaActions?.highlight(path, type, index);
                    }
                },
                args: [path, type, index],
            },
            (results) => {
                console.log(results);
            },
        );
    });
}

// 开始
async function onStart() {
    const rules = await readFromStorageAsync();
    if (!rules) {
        alert('获取规则失败');
        return;
    }
    // 获取当前 tab 页面
    chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
        const currentTab = tabs[0];
        const tabId = currentTab.id;

        // 正常页面
        if (isChromeTabUrl(currentTab.url)) {
            return;
        }

        // 在当前页面执行脚本，获取所有 button 元素
        chrome.scripting.executeScript(
            {
                target: { tabId },
                func: (rules) => {
                    if (typeof uiaActions !== 'undefined') {
                        return uiaActions?.validate(rules);
                    }
                },
                args: [rules],
            },
            (results) => {
                // 获取并显示脚本执行结果
                validateResult = results?.[0]?.result;
                if (validateResult) {
                    validateResult.tabId = tabId;
                    chrome.storage.local.set({ validateResult }, () => {
                        if (chrome.runtime.lastError) {
                            document.getElementById('statusMessage').textContent = 'Error saving data.';
                        } else {
                            // 保存成功后执行
                            renderResult();
                        }
                    });
                }
            },
        );
    });
}

function renderResult() {
    if (!validateResult) return;
    try {
        let str = `
        <ul id="list" class="popup-list">`;
        for (const item of validateResult.data) {
            const { validator, description, data } = item;

            for (const dataItem of data) {
                const { attribute, data, message } = dataItem;
                str += `
                    <li class="popup-item pupup-bg"> 
                        <div class="popup-box">
                            <span class="popup-label">验证描述:</span>
                            <span class="popup-value">${description}</span>
                        </div>
                        <div class="popup-box">
                            <span class="popup-label">验证属性:</span>
                            <span class="popup-value">${attribute}</span>
                        </div>
                        <div class="popup-box">
                            <span class="popup-label">验证结果:</span>
                            <span class="${
                                data.length > 0 ? 'popup-value popup-error-text' : 'popup-value popup-success-text'
                            }">${message}</span>
                        </div>
                       `;

                if (data.length > 0) {
                    str += ` <div class="popup-box">
                            <span class="popup-label">失败列表:</span>
                            <ul class="popup-list">`;

                    if (validator === 'exist-validator') {
                        let eleIndex = 0;
                        for (const datItem of data) {
                            const { paths } = datItem;
                            str += `
                                    <li class="popup-item">
                                        <div class="popup-box">
                                            <span class="popup-label">元素${(eleIndex += 1)}:</span>
                                            <ul class="popup-list">
                                            `;

                            for (const pathItem of paths) {
                                const { path, index, description } = pathItem;
                                str += ` 
                                                <li class="popup-item">
                                                    <div>
                                                        <span class="popup-label">path:</span>
                                                        <span class="popup-value">${path}</span>
                                                    </div>
                                                    <div>
                                                        <span class="popup-label">索引:</span>
                                                        <span class="popup-value">${index + 1}</span>
                                                    </div>
                                                    <div>
                                                        <span class="popup-label">描述:</span>
                                                        <span class="popup-value">${description}</span>
                                                    </div>
                                                </li>
                                                `;
                            }

                            str += `
                                            </ul>
                                        </div>
                                        <button 
                                        class="popup-button" 
                                        data-path="${paths[0].path}"
                                        data-type="${paths[0].type}"
                                        data-index="${paths[0].index}"
                                        >高亮</button>
                                    </li>`;
                        }
                    } else if (validator === 'unique-validator') {
                        for (const dataItem of data) {
                            const { value, count } = dataItem;
                            const dataPath = {
                                path: `[${attribute}='${value}']`,
                                index: -1,
                                type: 'selector',
                            };
                            JSON.stringify(dataPath);
                            str += `
                            <li class="popup-item">
                                <div class="popup-box">
                                    <span class="popup-label">元素属性:</span>
                                    <span class="popup-value">${attribute}=${value}</span>
                                    
                                </div>
                                <div class="popup-box">
                                    <span class="popup-label">元素个数:</span>
                                    <span class="popup-value">${count}</span>
                                </div>
                                <button 
                                    class="popup-button" 
                                    data-path="${dataPath.path}"
                                    data-type="${dataPath.type}"
                                    data-index="${dataPath.index}" 
                                >
                                        高亮
                                </button>
                        </li>`;
                        }
                    }
                    str += '</ul>';
                }
            }
        }
        str += `
        </ul>`;
        document.getElementById('result').innerHTML = str;
        const btns = document.getElementById('result').querySelectorAll('.popup-button');
        btns.forEach((btn) => {
            btn.addEventListener('click', onHighlight);
        });
        // document.getElementById('json').textContent = '检测结果:\n' + JSON.stringify(validateResult, null, 2);
    } catch (error) {
        console.error(error);
    }
}

// 上报结果
function reportResult() {
    if (!validateResult) {
        alert('No data available to export.');
        return;
    }

    // 创建一个 Blob 对象来存储 JSON 数据
    const jsonBlob = new Blob([JSON.stringify(validateResult, null, 2)], { type: 'application/json' });

    // 创建下载链接
    const url = URL.createObjectURL(jsonBlob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `result-${new Date().toLocaleDateString()}.json`; // 设置下载文件的默认名称
    a.click();

    // 释放 Blob URL
    URL.revokeObjectURL(url);
}

// 获取 Start 按钮并为其添加点击事件
document.getElementById('startButton').addEventListener('click', onStart);

// 导出数据为 JSON 文件
document.getElementById('reportResult').addEventListener('click', reportResult);
